package com.feng.filter;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.feng.entity.User;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    String userId = null;
    @Override
    public void insertFill(MetaObject metaObject) {
        try{
            User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            userId = user.getAccount().getId();
        }catch (Exception e){
            userId = "-1";
        }
        this.setFieldValByName("createBy", userId, metaObject);
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", userId, metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try{
            User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            userId = user.getAccount().getId();
        }catch (Exception e){
            userId = "-1";
        }
        this.setFieldValByName("updateBy", userId, metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}